package com.oocl.printer.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Set;

import com.oocl.pojo.Customer;
import com.oocl.printer.FilePrinter;

/**
 * 文件输出实现
 * 
 * @author GANAB
 * 
 */
public class FilePrinterImpl implements FilePrinter {
	
	private BufferedWriter bufferedWriter = null;
	
	public boolean print(Set<Customer> customers, String format, File file) throws Exception {
		StringBuilder sb = null;
		if ("xml".equals(format)) {
			sb = new StringBuilder();
			sb.append("<Customers>\r\n");
			for (Customer c : customers) {
				sb.append("<Customer id=\"" + c.getId() + "\" >\r\n");
				sb.append("<name>" + c.getName() + "</name>");
				sb.append("<email>" + c.getEmail() + "</email>");
				sb.append("<sex>" + c.getSex() + "</sex>");
				sb.append("<birthday>" + c.getBirthday() + "</birthday>\r\n");
				sb.append("</Customer>\r\n");
			}
			sb.append("</Customers>\r\n\r\n");
		} else if ("line".equals(format)) {
			sb = new StringBuilder();
			sb.append("ID Name Email Sex birthday\r\n");
			for (Customer c : customers) {
				sb.append(c.getId()+" " + c.getName()+ " " + c.getEmail() +" " +  c.getSex() + " " + c.getBirthday() +"\r\n");
			}
			System.out.println("\r\n");
		}
		
		if(sb!=null){
			bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			bufferedWriter.write(sb.toString());
			bufferedWriter.close();
			return true;
		}

		return false;
	}

}
